package com.linzm.leetcode.mid.tree.层次遍历;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

/**
 * @Author zimingl
 * @Date 2023/2/23 20:03
 * @Description: TODO
 */
public class Demo {
    public static void main(String[] args) {
        Demo demo = new Demo();
        List<List<Integer>> list = demo.leverOrderTraversalDFS(TreeNode.getTree());
        System.out.println(list);
    }

    private List<List<Integer>> leverOrderTraversalBFS(TreeNode root) {
        if (root == null) return new ArrayList<>();
        List<List<Integer>> res = new ArrayList<>();
        Deque<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            List<Integer> list = new ArrayList<>();
            int len = queue.size();
            while (len > 0) {
                root = queue.poll();
                list.add(root.val);
                if (root.left != null) queue.add(root.left);
                if (root.right != null) queue.add(root.right);
                len--;
            }
            res.add(list);
        }
        return res;
    }

    private List<List<Integer>> leverOrderTraversalDFS(TreeNode root) {
        if (root == null) return new ArrayList<>();
        List<List<Integer>> res = new ArrayList<>();
        dfs(root, res, 0);
        return res;
    }

    private void dfs(TreeNode treeNode, List<List<Integer>> res, int depth) {
        if (treeNode == null) return;
        depth++;
        if (depth > res.size()) {
            List<Integer> list = new ArrayList<>();
            res.add(list);
        }
        res.get(depth - 1).add(treeNode.val);
        dfs(treeNode.left, res, depth);
        dfs(treeNode.right, res, depth);
    }
}
